package ca.uwo.android.alumni;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import ca.uwo.android.BaseListMenuActivity;
import ca.uwo.android.R;
import ca.uwo.android.rss.RssFeed;
import ca.uwo.android.rss.RssItem;
import ca.uwo.android.rss.SaxRssParser;

public class AlumniNotable extends BaseListMenuActivity {

	private LayoutInflater mInflater;
	
	private String url;	//url of rss feed
	private RssFeed rssResults;	//rss feed to store rss items from feed

	// static final String[] title = new String[] {
	// "*New*Apple iPad Wi-Fi (16GB)", "7 Touch Tablet -2GB Google Android",
	// "Apple iPad Wi-Fi (16GB) Rarely Used ","Apple iPad Wi-Fi (16GB) AppleCase"
	// };
	// static final String[] detail = new String[] {
	// "1h 37m Shipping: $10.00","1h 39m Shipping: Free","58m 6s Shipping:
	// $10.00","59m 30s Shipping: $10.95" };
	// private Integer[] imgid = {
	// R.drawable.bsfimg,R.drawable.bsfimg4,R.drawable.bsfimg2,
	// R.drawable.bsfimg5
	// };
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newsfeedmain);
		
		//get the url, feed type and header title from framework
		url = getIntent().getExtras().getString("URL");
		
		//set header
		String newsFeedHeader = getIntent().getExtras().getString("HEADER");
		((TextView)findViewById(R.id.newsFeedHeader)).setText(newsFeedHeader);
		
		//parse feed
		loadRssFeed();
		
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		
		CustomAdapter adapter = new CustomAdapter(this, this.getListView().getId(),
				R.id.alumni_notable_title, rssResults.getItems());
		setListAdapter(adapter);
		getListView().setTextFilterEnabled(true);
	}

	public void onListItemClick(ListView parent, View v, int position, long id) {
				
				RssItem clickedItem = rssResults.get(position);	//get clicked item
				String clickedItemUrl = clickedItem.getLink();	//get url for clicked item
				
				Intent openFeedUrl = new Intent(Intent.ACTION_VIEW, Uri.parse(clickedItemUrl));
				startActivity(openFeedUrl);
	
	}



	private class CustomAdapter extends ArrayAdapter<RssItem> {
		
		int listViewId;
		
		public CustomAdapter(Context context, int resource,
				int textViewResourceId, List<RssItem> objects) {
			super(context, resource, textViewResourceId, objects);
			this.listViewId = resource;
		}

		@Override
		public View getView(int position, View convertView, android.view.ViewGroup parent) {

			ViewHolder holder = null;
			TextView title = null;
			TextView detail = null;
			ImageView i11 = null;
			RssItem rowData = getItem(position);
			if (null == convertView) {
				convertView = mInflater.inflate(R.layout.alumni_notable_newsfeed, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}
			holder = (ViewHolder) convertView.getTag();
			title = holder.gettitle();
			title.setText(rowData.getTitle());
			detail = holder.getdetail();
			detail.setText(Html.fromHtml(rowData.getDescription()));
			i11 = holder.getImage();
			
			try {
				  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(rowData.getImage()).getContent());
				  i11.setImageBitmap(bitmap); 
				} catch (MalformedURLException e) {
				  e.printStackTrace();
				} catch (IOException e) {
				  e.printStackTrace();
				}

			return convertView;
		}

		private class ViewHolder {
			private View mRow;
			private TextView title = null;
			private TextView detail = null;
			private ImageView i11 = null;

			public ViewHolder(View row) {
				mRow = row;
			}

			public TextView gettitle() {
				if (null == title) {
					title = (TextView) mRow.findViewById(R.id.alumni_notable_title);
				}
				return title;
			}

			public TextView getdetail() {
				if (null == detail) {
					detail = (TextView) mRow.findViewById(R.id.alumni_notable_detail);
				}
				return detail;
			}

			public ImageView getImage() {
				if (null == i11) {
					i11 = (ImageView) mRow.findViewById(R.id.alumni_notable_img);
				}
				return i11;
			}
		}
	}
	//========================================================
	
	
		
	
	/**
	 * This method is used to connect to, retrieve, parse and display the rss feed data
	 * from a rss feed url.
	 */
	public void loadRssFeed() {
		try {
			//retreive and parse the rss feedLog.
			SaxRssParser rssParser = new SaxRssParser(url);
			rssResults = rssParser.parse();
			
			
		} catch (Exception e) {
			
//			Log.e("RssNewsFeed loadRssFeed", "Exception reading feed", e);
			
			//create empty alert dialog
			AlertDialog alert = new AlertDialog.Builder(this)
			.setTitle("Error")
	        .setIcon(android.R.drawable.ic_dialog_alert)
	        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		                finish();	//close the current activity and return to the previous one
		            }
		        })
	        .create();
			
			//Error checking
			if(e instanceof MalformedURLException){
				alert.setMessage("The URL for the RSS feed is invalid!");
			}
			else if(e instanceof SAXException){
				alert.setMessage("The RSS feed could not be parsed!");
				e.printStackTrace();
//				Log.e("RssNewsFeed", "Error parsing:  " + e.getMessage());
			}
			else if(e instanceof IOException){
				alert.setMessage("Could not establish a connection to the RSS feed!");
			}
			else{
				alert.setMessage("There was a problem while parsing the RSS feed!");
			}
			alert.show();	//show populated alert dialog based on error type
		}
	}
}
